﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OfficeOpenXml;

namespace MoneyWentWhere.DataModel.Storage
{
    static class ExcelExtensionMethods
    {
        public static bool Delete(this ExcelWorksheets doc, String name)
        {
            for (int pos = 1; pos < doc.Count + 1; pos++)
            {
                if (doc[pos].Name == name)
                {
                    doc.Delete(pos);
                    return true;
                }
            }
            return false;
        }

        public static ExcelWorksheet GetOrCreateWorksheet(this ExcelWorksheets doc, String name)
        {
            ExcelWorksheet ws = doc[name];
            if (ws == null)
            {
                ws = doc.Add(name);
            }
            return ws;
        }

        public static void WriteRow(this ExcelWorksheet ws, String style, int row, params object[] vals)
        {
            WriteRow(ws, row, vals);
            SetRowStyle(ws, style, row, vals.Length);
        }

        public static void WriteRow(this ExcelWorksheet ws, int row, params object[] vals)
        {
            for (int i = 0; i < vals.Length; i++)
            {
                String strVal;

                if (vals[i] == null) { strVal = String.Empty; }
                // BUGFIX, 0m.ToString() = "0.0000" which doesn't serialize well
                else if (vals[i] is decimal && 0m.Equals(vals[i])) { strVal = "0"; } 
                else { strVal = vals[i].ToString(); }
                
                strVal = strVal.Replace("'", "`");
                ws.Cell(row, i + 1).Value = strVal;
            }
        }

        public static void SetRowStyle(this ExcelWorksheet ws, String style, int row, int numCols)
        {
            if (style == null) { style = ""; }
            for (int i = 0; i < numCols; i++)
            {
                ws.Cell(row, i + 1).Style = style;
            }            
        }

        public static void DeleteRemainingRows(this ExcelWorksheet ws, int startRowIndex, int numCols)
        {
            while (!RowIsEmpty(ws, startRowIndex, numCols))
            {
                ws.DeleteRow(startRowIndex, false);
                ++startRowIndex;
            }
        }

        public static bool RowIsEmpty(this ExcelWorksheet ws, int rowIndex, int numCols)
        {
            for (int i = 0; i < numCols; i++)
            {
                if (!String.IsNullOrEmpty(ws.Cell(rowIndex, i + 1).Value)) { return false; }
            }
            return true;
        }

    }
}
